import enums.RequestMethod;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * @Author zhangkaiqiang
 * @Date 2020/1/31  17:24
 * @Description TODO
 */
public class HttpUtil<T> {


	/**
	 * 进行实际的请求发生
	 * @param requestUrl 请求路径
	 * @param method 请求方法
	 * @param params 请求参数
	 * @return 请求结果字符串
	 */
	public static String postRequest(String requestUrl, RequestMethod method,Map<String,Object> params){
		try {
			// 设置请求路径与开启连接
			URL url=new URL(requestUrl);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod(method.name());
			connection.setDoOutput(true);

			// 输出流写出参数
			connection.getOutputStream().write(spiltParam(params));

			// 建立实际的网络连接
			connection.connect();

			InputStream inputStream=connection.getInputStream();


			// 得到响应
			String response=copyToString(inputStream, Charset.forName("UTF-8"));

			inputStream.close();

			return response;

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}


	/**
	 * 进行参数的拼接
	 * @param params 待发送的参数
	 * @return 拼接好的请求参数
	 */
	private static byte[] spiltParam(Map<String,Object> params) throws UnsupportedEncodingException {
		if(params==null || params.size()<=0){
			return new byte[0];
		}
		int i=0;
		StringBuilder builder=new StringBuilder();
		Set<Map.Entry<String, Object>> entries = params.entrySet();
		Iterator<Map.Entry<String, Object>> iterator = entries.iterator();
		while(iterator.hasNext()){
			Map.Entry<String, Object> entry=iterator.next();
			if(i!=0){
				builder.append("&");
			}
			builder.append(entry.getKey()).append("=").append(entry.getValue());
			i++;
		}
		return builder.toString().getBytes("UTF-8");
	}


	/**
	 * 从输入流得到字符串
	 * @param in 请求结果输入流
	 * @param charset 设置输入流的编码方式
	 * @return 请求结果的字符串表示
	 * @throws IOException
	 */
	private static String copyToString( InputStream in, Charset charset) throws IOException {
		if (in == null) {
			return "";
		}
		StringBuilder builder = new StringBuilder();
		InputStreamReader reader = new InputStreamReader(in, charset);
		char[] buffer = new char[4096];
		int bytesRead;
		while((bytesRead = reader.read(buffer)) != -1) {
			builder.append(buffer, 0, bytesRead);
		}
		return builder.toString();
	}





	public static void main(String[] args) {
		Map<String,Object> param=new HashMap<>();
		param.put("shouji","13054626536");
		param.put("appkey","");
		String re=postRequest("http://way.jd.com/jisuapi/query4",RequestMethod.POST,param);
		System.out.println(re);
	}
}
